<script setup lang='ts'>
import type { UploadProps } from 'element-plus'
import piexif from 'piexifjs'
import { exifTagsChinese, formatExifValue } from '~/composables/exif'

const imageUrl = ref('')
const exifData = ref<any>({
  '0th': {
    256: 3072,
    257: 4096,
    259: 6,
    271: 'Xiaomi',
    272: '2112123AC',
    274: 1,
    282: [
      72,
      1,
    ],
    283: [
      72,
      1,
    ],
    296: 2,
    306: '2025:08:31 14:20:38',
    531: 1,
    34665: 246,
    34853: 813,
  },
  'Exif': {
    33434: [
      100,
      10000,
    ],
    33437: [
      18800,
      10000,
    ],
    34850: 2,
    34855: 151,
    36864: '0220',
    36867: '2025:08:31 14:20:38',
    36868: '2025:08:31 14:20:38',
    37121: '???',
    37377: [
      66438,
      10000,
    ],
    37378: [
      18215,
      10000,
    ],
    37379: [
      224,
      100,
    ],
    37380: [
      0,
      6,
    ],
    37381: [
      18215,
      10000,
    ],
    37382: [
      890,
      10000,
    ],
    37383: 2,
    37384: 21,
    37385: 16,
    37386: [
      55900,
      10000,
    ],
    37520: '338',
    37521: '338',
    37522: '338',
    40960: '0100',
    40961: 1,
    40962: 3072,
    40963: 4096,
    40965: 1025,
    41495: 1,
    41729: '1',
    41986: 0,
    41987: 0,
    41988: [
      0,
      10000,
    ],
    41989: 24,
    41990: 0,
    41996: 1,
  },
  'GPS': {
    1: 'N',
    2: [
      [
        35,
        1,
      ],
      [
        6,
        1,
      ],
      [
        34002000,
        1000000,
      ],
    ],
    3: 'E',
    4: [
      [
        118,
        1,
      ],
      [
        21,
        1,
      ],
      [
        5454000,
        1000000,
      ],
    ],
    5: 0,
    6: [
      0,
      1000,
    ],
    7: [
      [
        6,
        1,
      ],
      [
        20,
        1,
      ],
      [
        36,
        1,
      ],
    ],
    27: 'CELLID',
    29: '2025:08:31',
  },
  'Interop': {
    1: 'R98',
  },
  '1st': {},
  'thumbnail': null,
})
const uploadError = ref('')
const longitude = ref('119.514152')
const latitude = ref('35.411515')

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: File) => {
  // 检查文件类型
  if (!rawFile.type.includes('image')) {
    uploadError.value = '请上传图片文件'
    return false
  }

  // 读取文件
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const dataUrl = e.target?.result as string
      imageUrl.value = dataUrl

      // 读取EXIF信息
      const exifObj = piexif.load(dataUrl)
      console.log('读取内容', piexif.load(dataUrl))

      // exifData.value = exifObj
      uploadError.value = ''
    }
    catch (error) {
      console.error('读取EXIF信息失败:', error)
      uploadError.value = '读取图片EXIF信息失败'
      // exifData.value = null
    }
  }
  reader.readAsDataURL(rawFile)

  return false
}

// 获取标签的中文名称
function getTagName(ifdName: string, tag: number) {
  // piexifjs使用数字作为键
  return exifTagsChinese[ifdName]?.[tag] || tag.toString()
}

// 保存修改后的EXIF数据到文件
function saveWithExif() {
  if (!imageUrl.value || !exifData.value) {
    return
  }

  try {
    // 创建EXIF数据的副本
    const newExifObj = JSON.parse(JSON.stringify(exifData.value))
    console.log(1, newExifObj)

    // 如果用户输入了经纬度，则更新GPS信息
    if (longitude.value && latitude.value) {
      // 初始化GPS IFD（如果不存在）
      if (!newExifObj.GPS) {
        newExifObj.GPS = {}
      }

      // 设置GPS经纬度参考方向
      newExifObj.GPS[3] = Number(longitude.value) >= 0 ? 'E' : 'W' // GPSLongitudeRef
      newExifObj.GPS[1] = Number(latitude.value) >= 0 ? 'N' : 'S' // GPSLatitudeRef

      // 转换经纬度为DMS格式
      const lon = convertToDMS(Math.abs(Number(longitude.value)))
      const lat = convertToDMS(Math.abs(Number(latitude.value)))

      // 设置GPS经纬度
      newExifObj.GPS[4] = lon // GPSLongitude
      newExifObj.GPS[2] = lat // GPSLatitude
    }

    // 生成EXIF字符串
    const exifStr = piexif.dump(newExifObj)
    console.log('写入内容', exifStr)

    // 插入EXIF数据到图片
    const insertedData = piexif.insert(exifStr, imageUrl.value)

    // 下载文件
    const link = document.createElement('a')
    link.href = insertedData
    link.download = 'modified-image.jpg'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
  catch (error) {
    console.error('保存EXIF信息失败:', error)
    uploadError.value = '保存EXIF信息失败'
  }
}

// 将十进制坐标转换为DMS格式
function convertToDMS(decimal: number): [number, number][] {
  const degrees = Math.floor(decimal)
  const minutes = Math.floor((decimal - degrees) * 60)
  const seconds = (decimal - degrees - minutes / 60) * 3600 * 100000

  return [
    [degrees, 1],
    [minutes, 1],
    [Math.round(seconds), 1000000],
  ]
}
</script>

<template>
  <div class="min-h-screen p-4">
    <el-upload class="min-h-40 b b-white b-dashed" :show-file-list="false" drag :before-upload="beforeAvatarUpload">
      <div class="h-full">
        <img v-if="imageUrl" :src="imageUrl" class="h-full w-full object-contain">
        <div v-else class="h-full w-full flex-center">
          <div class="text-center">
            <div class="i-ic-round-cloud-upload b b-red text-3xl" />
            <div class="">上传图片</div>
          </div>
        </div>
      </div>
    </el-upload>

    <div v-if="uploadError" class="mt-4 text-red">
      {{ uploadError }}
    </div>

    <div v-if="exifData" class="mt-4">
      <h3 class="mb-2 text-lg font-bold">EXIF 信息:</h3>

      <!-- 经纬度输入框 -->
      <div class="mb-4 rounded p-4">
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <el-input v-model="longitude" placeholder="经度 (例如: 121.567890)" clearable>
            <template #prepend>经度</template>
          </el-input>
          <el-input v-model="latitude" placeholder="纬度 (例如: 31.123456)" clearable>
            <template #prepend>纬度</template>
          </el-input>
        </div>
        <div class="mt-4 flex justify-center">
          <el-button type="primary" @click="saveWithExif">
            保存并下载
          </el-button>
        </div>
      </div>

      <!-- EXIF信息展示 -->
      <el-collapse>
        <el-collapse-item v-for="(ifd, ifdName) in exifData" :key="ifdName" :name="ifdName.toString()" :title="ifdName.toString()">
          <div class="grid grid-cols-1 gap-2 p-2 md:grid-cols-2">
            <div v-for="(value, tag) in ifd" :key="tag" class="flex">
              <span class="w-32 flex-shrink-0 text-sm font-mono">{{ getTagName(ifdName.toString(), Number(tag)) }}:</span>
              <span v-if="typeof value === 'string'" class="ml-2 break-all text-sm">
                {{ value }}
              </span>
              <span v-else class="ml-2 break-all text-sm">
                {{ formatExifValue(tag.toString(), value) }}
              </span>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-upload) {
  display: block !important;
  height: 100%;
}

:deep(.el-collapse) {
  border-radius: 0.25rem;
  overflow: hidden;
}
</style>

<route lang='yaml'>
meta:
  title: '首页'
</route>
